package handler

import (
	"strconv"
	"web_framework/model"
	"web_framework/pkg/constvar"
	"web_framework/pkg/e"
	"web_framework/service"
	"web_framework/storage"
)

//登录身份验证
type GetTaskListHandle struct {
}

func (getTaskListHandle GetTaskListHandle) handleMsg(data model.Request, clientId string) (result model.Response) {
	if data.Mtype == constvar.MtypeAppGetTaskListRequest {
		//检查参数是否为空
		if len(data.Data.Sn) == 0 {
			e.Log("Info", "sn参数异常")
			return ReturnErr(data.Mid, constvar.MtypeAppGetTaskListResponse, "sn参数异常")
		}
		tasks := []model.Task{}
		loadTaskQueueCacheKey := constvar.RouterRedisPrefix + data.Data.Sn + storage.RedisRouterTaskGoingSetKey
		res, _ := service.GetTaskQueueInfoCache(loadTaskQueueCacheKey, data.Data.Sn, 20)
		for _, task := range res {
			taskIdInt64, _ := strconv.ParseInt(task["taskId"].(string), 10, 64)
			totalSize, _ := strconv.Atoi(task["totalSize"].(string))
			originStatus, _ := strconv.Atoi(task["status"].(string))
			downloadedSize, _ := strconv.Atoi(task["downloadedSize"].(string))
			taskSpeed,_ :=  strconv.Atoi(task["speed"].(string))
			//平台的任务状态转换未APP的任务状态
			var status int
			switch originStatus {
			case model.TaskStatusCreating:
				status = model.AppTaskCreating
			case model.TaskStatusWaiting:
				status = model.AppTaskWaiting
			case model.TaskStatusloading:
				status = model.AppTaskLoading
			case model.TaskStatusPauseing:
				status = model.AppTaskPausing
			case model.TaskStatusPaused:
				status = model.AppTaskPaused
			case model.TaskStatusDeleting:
				status = model.AppTaskDeleting
			case model.TaskStatusLoadFail:
				status = model.AppTaskLoadFail
			}

			loadTask := model.Task{
				TaskID:       taskIdInt64,
				TotalSize:    totalSize,
				ResName:      task["name"].(string),
				Path:         task["path"].(string),
				Status:       status,
				URL:          task["url"].(string),
				DownloadSize: downloadedSize,
				Speed:        taskSpeed,
			}
			tasks = append(tasks, loadTask)
		}

		var returnData interface{} = tasks

		return model.Response{
			Mid:    data.Mid,
			Mtype:  constvar.MtypeAppGetTaskListResponse,
			Info:   "获取列表成功",
			Status: constvar.StatusOk,
			Data:   &returnData,
		}
	}
	e.Log("Info", "获取失败 103")
	return ReturnErr(data.Mid, constvar.MtypeAppGetTaskListResponse, "获取失败")
}
